package com.haitaoit.chengquan.module.center.activity.return_goods;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.home.model.TitleModel;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DialogUtil;
import com.haitaoit.chengquan.utils.GetAbserlutePath;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.utils.ZoomBitmap;
import com.haitaoit.chengquan.view.pickerview.OptionsPopupWindow;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

public class PlyReturnActivity extends BaseActivity {
    @ViewInject(R.id.return_reason_tv)
    TextView     return_reason_tv;
    @ViewInject(R.id.return_type)
    TextView     return_type;
    @ViewInject(R.id.return_money)
    EditText     return_money;
    @ViewInject(R.id.instructions)
    EditText     instructions;
    @ViewInject(R.id.return_img1)
    ImageView    return_img1;
    @ViewInject(R.id.return_img2)
    ImageView    return_img2;
    @ViewInject(R.id.return_img3)
    ImageView    return_img3;
    @ViewInject(R.id.linearlayout_upate)
    LinearLayout linearlayout_upate;

    private List<TitleModel> listTitle;
    private List<String> imgList = new ArrayList<>();
    private String reason_id, type = "1", order_no, amount = "", again;
    private int imgid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.plyreturnactivity);
        setTitle_V("申请退款");
        setLeftShow(1, R.mipmap.left);
        backLeft_V();
        ViewUtils.inject(this);


        order_no = getIntent().getStringExtra("order_no");
        amount = getIntent().getStringExtra("amount");
        again = getIntent().getStringExtra("again");
        return_money.setHint("最多可退" + amount + "元");
        linearlayout_upate.setVisibility(View.GONE);
        HttpGetorder_refund_reason_list();
    }

    @OnClick({R.id.return_type, R.id.return_reason, R.id.return_img1, R.id.return_img2,
            R.id.return_img3, R.id.return_go,})
    public void onClick(View v) {// 收起键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        switch (v.getId()) {
            case R.id.return_type:
//                updateType();
                break;
            case R.id.return_reason:
                Dialog dlg = DialogUtil.ShowReturnDialog(this, listTitle, new BackCall() {
                    @Override
                    public void deal(int which, Object... obj) {
                        int position = (Integer) obj[0];
                        switch (which) {
                            case R.id.sure:// 确定
                                return_reason_tv.setText(listTitle.get(position).getName());
                                reason_id = listTitle.get(position).getId();
                                break;
                        }
                        super.deal(which, obj);
                    }
                });
                dlg.setCanceledOnTouchOutside(true);
                dlg.show();
                DisplayMetrics metric = new DisplayMetrics();
                this.getWindowManager().getDefaultDisplay().getMetrics(metric);
                WindowManager.LayoutParams params = dlg.getWindow().getAttributes();
                params.height = metric.heightPixels; // 屏幕高度（像素）
                params.width = metric.widthPixels * 3 / 4; // 屏幕高度（像素）
                params.gravity = Gravity.RIGHT;
                dlg.getWindow().setAttributes(params);
                break;
            case R.id.return_img1:
                imgid = 1;
                SelectPhoto();
                break;
            case R.id.return_img2:
                imgid = 2;
                SelectPhoto();
                break;
            case R.id.return_img3:
                imgid = 3;
                SelectPhoto();
                break;
            case R.id.return_go:// 提交
                if (return_money.getText().toString().equals("")) {
                    ToastUtils.showToast("请输入退款金额！");
                } else if (Float.valueOf(amount) < Float.valueOf(return_money.getText().toString())) {
                    ToastUtils.showToast("输入的退款金额大于实付金额！");
                } else if (return_reason_tv.getText().toString().equals("")) {
                    ToastUtils.showToast("请选择原因！");
                } else if (instructions.getText().toString().equals("")) {
                    ToastUtils.showToast("请输入说明！");
                } else {
                    httpadd_order_after_sales();
                }
                break;
        }
        super.onClick(v);
    }

    // 提交
    private void httpadd_order_after_sales() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("order_no", order_no));
        list.add(new NameValuePairSign("type", type));
        list.add(new NameValuePairSign("count", again));
        list.add(new NameValuePairSign("refund_money", return_money.getText().toString()));
        list.add(new NameValuePairSign("refund_reason_id", reason_id));
        list.add(new NameValuePairSign("instructions", instructions.getText().toString()));
        String sign = GetSign.genPackageSign(list);

        String url = Constant.add_order_after_sales + "user_id=" + PreferenceUtils.getPrefString("user_id", "")
                + "&type=" + type + "&order_no=" + order_no + "&count=" + again + "&refund_money=" +
                return_money.getText().toString() + "&refund_reason_id=" + reason_id +
                "&instructions=" + instructions.getText().toString() + "&sign=" + sign;
        JSONObject params = new JSONObject();
        try {
            JSONArray house_imgs = new JSONArray();
            for (int i = 0; i < imgList.size(); i++) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("img_url", imgList.get(i));
                house_imgs.put(jsonObject);
            }
            params.put("img", house_imgs);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }

        HttpUtilsSingle.doPost(this, true, url, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            break;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            setResult(1);
                            finish();
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 退款原因分类列表
    private void HttpGetorder_refund_reason_list() {
        int i = (int) Math.floor(Math.random() * 9000 + 1000);
        final List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("rnd", i + ""));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("rnd", i + "");
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getorder_refund_reason_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            listTitle = gson.fromJson(Response,
                                    new TypeToken<List<TitleModel>>() {
                                    }.getType());
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    public void SelectPhoto() {
        Dialog dlg = DialogUtil.ShowPhotoDialog(this, new BackCall() {
            @Override
            public void deal(int which, Object... obj) {
                switch (which) {
                    case R.id.tv_photos:// 图库
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        intent.addCategory(Intent.CATEGORY_OPENABLE);
                        intent.setType("image/*");
                        intent.putExtra("aspectX", 1);
                        intent.putExtra("aspectY", 1);
                        intent.putExtra("outputX", 500);
                        intent.putExtra("outputY", 500);
                        intent.putExtra("crop", "true");
                        intent.putExtra("return-data", true);
                        startActivityForResult(intent, 2);
                        break;
                    case R.id.tv_camera:
                        Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(in, 2);
                        break;
                }
                super.deal(which, obj);
            }
        });
        dlg.setCanceledOnTouchOutside(true);
        dlg.show();

        DisplayMetrics metric = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels; // 屏幕宽度（像素）
        WindowManager.LayoutParams params = dlg.getWindow().getAttributes();
        params.width = width;
        params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
        dlg.getWindow().setAttributes(params);
    }

    // 记录文件名
    private String filename;
    // 上传的bitmap
    private Bitmap upbitmap;
    private String file1 = "", file2 = "", file3 = "";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1: // 解成bitmap,方便裁剪
                Bitmap bitmap = BitmapFactory.decodeFile(Environment
                        .getExternalStorageDirectory().getPath() + "/" + filename);
                float wight = bitmap.getWidth();
                float height = bitmap.getHeight();
                ZoomBitmap.zoomImage(bitmap, wight / 8, height / 8);
                upbitmap = ZoomBitmap.zoomImage(bitmap, wight / 19, height / 19);
//                center_img.setImageBitmap(upbitmap);
                break;
            case 2:
                if (data != null) {
                    upbitmap = null;
                    if (data.getExtras() != null && !("").equals(data.getExtras())) {
                        upbitmap = (Bitmap) data.getExtras().get("data");
                    } else {
                        String str = data.getDataString();
                        if (str == null) {
                            return;
                        }
                        Uri uri = Uri.parse(str);
                        String path = GetAbserlutePath.getPath(this, uri);
                        if (path.endsWith("png") || path.endsWith("jpg")) {// 图片
                            upbitmap = ImageLoader.getInstance().loadImageSync("file://" + path);
                        } else {
                            ToastUtils.showToast("请选择.jpg或.png格式的图片！");
                            return;
                        }
                    }
                    upbitmap = getSmallBitmap(upbitmap);
                    if (imgid == 1) {
                        file1 = bitmapToString(upbitmap);
                        return_img1.setImageBitmap(upbitmap);
                        imgList.add(file1);
                    } else if (imgid == 2) {
                        file2 = bitmapToString(upbitmap);
                        return_img2.setImageBitmap(upbitmap);
                        imgList.add(file2);
                    } else if (imgid == 3) {
                        file3 = bitmapToString(upbitmap);
                        return_img3.setImageBitmap(upbitmap);
                        imgList.add(file3);
                    }
                }
                break;
        }
    }
    // 把bitmap转换成String
    public static String bitmapToString(Bitmap bgimage) {
        Bitmap bm = getSmallBitmap(bgimage);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);
        byte[] b = baos.toByteArray();
        return Base64.encodeToString(b, Base64.DEFAULT);
    }

    // 根据路径获得图片并压缩，返回bitmap用于显示
    public static Bitmap getSmallBitmap(Bitmap bgimage) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 480, 800);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        // return BitmapFactory.decodeFile(filePath, options);
        return ZoomBitmap.zoomImage(bgimage, bgimage.getWidth()
                / options.inSampleSize, bgimage.getHeight() / options.inSampleSize);
    }

    // 计算图片的缩放值
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    private void updateType() {
        final List<TitleModel> list = new ArrayList<>();
        list.add(new TitleModel("1", "退款"));
        list.add(new TitleModel("2", "退货"));
        list.add(new TitleModel("3", "换货"));

        final ArrayList<String> list2 = new ArrayList<String>();
        for (int i = 0; i < list.size(); i++) {
            list2.add(list.get(i).getName());
        }

        OptionsPopupWindow popSex = new OptionsPopupWindow(this, "");
        popSex.setPicker(list2);
        popSex.setSelectOptions(0);
        popSex.setOnoptionsSelectListener(new OptionsPopupWindow.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                return_type.setText(list2.get(options1));
                type = list.get(options1).getId();
            }
        });
        popSex.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);// popupwindow消失的时候恢复成原来的透明度
            }
        });
        popSex.showAtLocation(return_type, Gravity.BOTTOM, 0, 0);
        backgroundAlpha(0.6f);
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;// 0.0-1.0
        getWindow().setAttributes(lp);
    }
}
